package socket.service;


import com.alibaba.fastjson.JSON;
import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import socket.utils.message.Message;
import socket.utils.message.MsgType;

/**
 * Created by think on 2017/10/30.
 */
@ChannelHandler.Sharable
public class EchoServerHandler extends SimpleChannelInboundHandler<String> {

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //channel失效，从Map中移除
        NettyChannelMap.remove((SocketChannel) ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        System.out.println("出现异常！");
    }

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println(msg);
        Message message = JSON.parseObject(msg + "", Message.class);
        System.out.println("接收到消息：" + message);
        String clientId = message.getClientId();
        if (MsgType.LOGIN.equals(message.getType())) {
            System.out.printf("将%s添加到队列\n", clientId);
            NettyChannelMap.add(clientId, (SocketChannel) ctx.channel());
        } else {
            if (NettyChannelMap.get(clientId) == null) {
                System.out.printf("登录失败，请重新登录!", clientId);
                //说明未登录，或者连接断了，服务器向客户端发起登录请求，让客户端重新登录
                message = new Message(MsgType.LOGIN);
                ctx.channel().writeAndFlush(JSON.toJSONString(message));
            }
        }
        switch (message.getType()) {
            case PING: {
                message = new Message(MsgType.PING);
                NettyChannelMap.get(clientId).writeAndFlush(JSON.toJSONString(message));
            }
            break;
            case SEND: {
                //收到客户端的请求，发送给targetId
                System.out.println("发送消息：" + message);
                if (NettyChannelMap.get(message.getTargetId()) != null) {
                    NettyChannelMap.get(message.getTargetId()).writeAndFlush(JSON.toJSONString(message));
                } else {
                    message.setType(MsgType.NO_TARGET);
                    NettyChannelMap.get(clientId).writeAndFlush(JSON.toJSONString(message));
                }
            }
            break;
            default:
                break;
        }
    }

}



